<template>
  <Container class="lottery-info">
    <div class="container-header title title-center" slot="header">
      活动设置
      <Button size="large" class="fl btn-back"  icon="ios-arrow-back" @click="$router.back()">返回</Button>
    </div>
    <div class="bg-light pt mb pb mt">
      <Form :label-width="100" :model="list.form" ref="form" :rules="rules">
        <FormItem label="活动名称：" prop="name">
          <Input :maxlength="20" class="wp40" v-model.trim="list.form.name" placeholder="请输入2-20位字符的活动名称"/>
        </FormItem>
        <FormItem label="科室：" prop="departmentIdSet">
          <CheckboxGroup v-model="list.form.departmentIdSet">
            <Checkbox :disabled="item.disabled" :label="item.id" v-for="(item, index) in  departmentList" :key="index">
              {{item.name}}
            </Checkbox>
          </CheckboxGroup> 
        </FormItem>
        <FormItem label="消耗云币：" prop="goldNum">
          <p>每次抽奖消耗<InputNumber class="ml mr" v-model="list.form.goldNum" precision="0" :min="1" :max="9999999999999999999999"></InputNumber>云币</p>
        </FormItem>
        <FormItem label="有效时间：" prop="time">
          <DatePicker v-model="list.form.time" type="datetimerange" format="yyyy-MM-dd HH:mm" placeholder="选择时间" style="width: 300px"></DatePicker>
        </FormItem>
        <FormItem label="上架">
          <Checkbox v-model="list.form.isEnable"></Checkbox>
        </FormItem>
      </Form>
    </div>
    <Tabs v-model="tab" v-if="id">
      <Button
        size="large"
        class="item"
        type="primary"
        slot="extra"
        icon="md-add"
        @click="onAddAward">新增奖品</Button>
      <TabPane label="奖品列表" name="tab1">
        <Table
          stripe
          :columns="list.columns"
          :data="list.data"
          no-data-text="亲，没有找到相关记录哦！~"></Table>
      </TabPane>
    </Tabs>
    <Loader :status="list.status" @refresh="getInfo"></Loader>
    <div class="container-footer bg-white" slot="footer">
      <Button type="primary" class="mr" size="large" :disabled="isDisabled" @click="onSave">确定</Button>  
    </div>
    <StockEditItem ref="stockEdit" @complete="getAllPrize"/>
    <AwardEditItem ref="awardEdit" :list="list.data" @complete="getAllPrize" />
  </Container>
</template>
<script>
import table from "@/table";
import lotterInfoList from './edit/LotteryInfoData'
import StockEditItem from './edit/StockEditItem'
import AwardEditItem from './edit/AwardEditItem'
import { formatDate, clearEmpty } from '@/util'
export default {
  components: {
    StockEditItem,
    AwardEditItem
  },
  data() {
    const checkGold = (rule, value, callback) => {
      if (value === undefined || value === null) {
        callback(new Error('请输入消耗金币数'))
      } else if (Number(value) < 1) {
        callback(new Error('消耗金币数至少为1'))
      }else {
        callback()
      }
    }
    return {
      id: this.$route.query.id || null,
      usedDepartment: [],
      isDisabled: false,
      tab: 'tab1',
      list: lotterInfoList,
      departmentList: [],
      rules: {
        name: [{required: true, message: '请输入活动名称', trigger: 'blur' }],
        goldNum: [{required: true, validator: checkGold, message: "请输入消耗金币数", trigger: "change"}],
        departmentIdSet: [{required: true, type: 'array', min: 1, message: '请选择科室', trigger: "change"}],
        time: [{required: true, message: '请选择时间'},
              {pattern: null, type: 'array', message: null}]
      },
      options: {
        tableHeight: 300
      }
    }
  },
  mounted() {
    this.$refs.form.resetFields()
    this.list.form = {
      name: '',
      departmentIdSet: [],
      time: [],
      goldNum: null,
      startTime: '',
      endTime: '',
      isEnable: false
    }
    this.$bus.$on("onAddStock", this.onAddStock);
    this.$bus.$on("onEdit", this.onEdit);
    this.$bus.$on("onDelete", this.onDelete);
    this.initTable(270)
    this.getDepartData()
    if (this.id) {
      this.getAllPrize()
    }
  },
  destroyed() {
    this.$bus.$off();
  },
  methods: {
    ...table,
    async getInfo() {
      this.list.status = 'loading'
      await this.$ajaxGet(`/lottery/rule/${this.id}`).then(data => {
        this.list.form = {...data}
        this.list.form.time = [data.startTime, data.endTime]
      }).catch(() => {
        this.list.status = 'error'
      })
    },
    async getUsedDepart() { // 获得已有活动的科室
      let param = {
        ruleId: this.id ? this.id : null
      }
      clearEmpty(param)
      await this.$ajaxGet(`/lottery/rule/department`, param).then(data => {
        this.usedDepartment = data.existDepartmentIds || []
      })
    },
    getDepartData() { // 所有科室
      this.list.status = 'loading'
      this.getUsedDepart().then(() => {
        this.$ajaxGet('/old/department').then(data => {
          this.departmentList = (data || []).map(item => {
            if (!this.id) this.list.status = 'pass' // 新建活动的时候，需要loading
            return {
              ...item,
              disabled: false
            }
          })
          this.usedDepartment.forEach(item => { // 已选的科室不能选
            this.departmentList.forEach(m => {
              if (item === m.id) m.disabled = true
            })
          })
        })
      })
    },
    getAllPrize() { // 所有奖品
      let parma = {
        lotteryId: this.id
      }
      this.list.data = []
      this.getInfo().then(() => {
        this.$ajaxGet(`/lottery/prize/find_lotteryId/${this.id}`).then(data => {
          this.list.status = 'pass'
          this.list.data = data || []
        })
      }).catch(() => {
        this.list.status = 'error'
      })
    },
    onAddAward() {
      this.$refs.awardEdit.resetForm(this.id)
    },
    onEdit(id) {
      this.$refs.awardEdit.updateForm(id, this.id)
    },
    onAddStock(id, lastStock) {
      this.$refs.stockEdit.resetForm(id, lastStock)
    },
    onDelete(id, name, index) {
      this.$Modal.confirm({
        title: "删除",
        content: "确定删除当前奖品？",
        onOk: () => {
          this.$ajaxPost(`/lottery/prize/del/${id}`).then(data => {
            this.$Notice.success({
              title: "删除成功",
              desc: `<span class="font-red">${name}</span> 已被删除。`
            });
            this.list.data.splice(index, 1)
          })
        }
      })
    },
    onSave() {
      if (this.isDisabled) return
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (!(this.list.form.time[0] && this.list.form.time[1] && this.list.form.time.length === 2)) {
            this.$Message.error('请选择时间')
            return
          }
					let param = {
            ...this.list.form
          }
          let departmentIdSet = this.list.form.departmentIdSet
          let departmentScope = ''
          departmentIdSet.forEach(item => {
            departmentScope += ',' + item
          })
          param.startTime = formatDate(this.list.form.time[0], true)
          param.endTime = formatDate(this.list.form.time[1], true)
          param.departmentScope = departmentScope
          this.isDisabled = true
          let url = this.id ? '/lottery/rule/edit' : '/lottery/rule/save'
          let text = this.id ? '编辑' : '新增'
          this.$jsonPost(url, param).then(data => {
            this.$Notice.success({
              title: `${text}成功`
            })
            this.$router.push('/sales/lottery/edit')
          }).catch(() => {
            this.isDisabled = false
          })
        }
      })
    }
  }
}
</script>
<style scoped>
.lottery-info .ivu-tabs {
  height: auto;
}
</style>